package valentini.android.strike;

import java.util.ArrayList;
import java.util.HashMap;

import valentini.android.strike.R;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

@SuppressLint("NewApi")
public class Finestra extends ListActivity {

	Intent intent;
	// action bar
	private ActionBar actionBar;

	// Refresh menu item
	public MenuItem refreshMenuItem;

	HtmlParser hp = null;
	ArrayList<HashMap<String, String>> menuItems = null;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		loadActivity();

	}

	private void loadActivity() {
		setContentView(R.layout.main);
		try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				actionBar = getActionBar();
				actionBar.setDisplayShowTitleEnabled(false);
			}

			if (isNetworkAvailable()) {
				try {
					hp = HtmlParser.getInstance();
					menuItems = hp.getItems();
				} catch (Exception e) {
					menuItems = new ArrayList<HashMap<String, String>>();
					HashMap<String, String> map = new HashMap<String, String>();
					showNoConnetionAlert();
				}
				
			} else {
				menuItems = new ArrayList<HashMap<String, String>>();
				HashMap<String, String> map = new HashMap<String, String>();
				// map.put(Constants.KEY_DATA, "Rete non disponibile");
				// menuItems.add(map);
				showNoConnetionAlert();
			}
			// Adding menuItems to ListView
			ListAdapter adapter = new SimpleAdapter(this, menuItems,
					R.layout.list_item, new String[] { Constants.KEY_DATA,
							Constants.KEY_CATEGORIA, Constants.KEY_MODALITA,
							Constants.KEY_SETTORE }, new int[] { R.id.dataList,
							R.id.categoriaList, R.id.modalitaList,
							R.id.settoreList });

			setListAdapter(adapter);

			ListView lv = getListView();
			lv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					String data = ((TextView) view.findViewById(R.id.dataList))
							.getText().toString();
					String modalita = ((TextView) view
							.findViewById(R.id.modalitaList)).getText()
							.toString();
					String categoria = ((TextView) view
							.findViewById(R.id.categoriaList)).getText()
							.toString();
					String settore = ((TextView) view
							.findViewById(R.id.settoreList)).getText()
							.toString();

					// Starting new intent
					Intent in = new Intent(getApplicationContext(),
							DettaglioSciopero.class);
					in.putExtra(Constants.KEY_DATA, data);
					in.putExtra(Constants.KEY_CATEGORIA, categoria);
					in.putExtra(Constants.KEY_MODALITA, modalita);
					in.putExtra(Constants.KEY_SETTORE, settore);
					startActivity(in);

				}
			});

		} catch (Exception e) {
			e.toString();
		}

	}

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main_actions, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * On selecting action bar icons
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Take appropriate action for each action item click
		switch (item.getItemId()) {
		case R.id.action_preferences:
			intent = new Intent(this, ConfigActivity.class);
			startActivity(intent);
			return true;
		case R.id.action_share:
			intent = new Intent(this, ConfigActivity.class);
			startActivity(intent);
			return true;
		case R.id.action_contact:
			// check for updates action
			contactMe();
			return true;
		case R.id.action_refresh:
			loadActivity();
			//populateList();
			return true;
		case R.id.action_info:
			intent = new Intent(getApplicationContext(), InfoActivity.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}


	private void populateList() {

		if (isNetworkAvailable()) {

			hp = HtmlParser.getInstance();

			menuItems = hp.getItems();
			// Adding menuItems to ListView
			ListAdapter adapter = new SimpleAdapter(this, menuItems,
					R.layout.list_item, new String[] { Constants.KEY_DATA,
							Constants.KEY_CATEGORIA, Constants.KEY_MODALITA,
							Constants.KEY_SETTORE }, new int[] { R.id.dataList,
							R.id.categoriaList, R.id.modalitaList,
							R.id.settoreList });

			setListAdapter(adapter);

			ListView lv = getListView();
			lv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					String data = ((TextView) view.findViewById(R.id.dataList))
							.getText().toString();
					String modalita = ((TextView) view
							.findViewById(R.id.modalitaList)).getText()
							.toString();
					String categoria = ((TextView) view
							.findViewById(R.id.categoriaList)).getText()
							.toString();
					String settore = ((TextView) view
							.findViewById(R.id.settoreList)).getText()
							.toString();

					// Starting new intent
					Intent in = new Intent(getApplicationContext(),
							DettaglioSciopero.class);
					in.putExtra(Constants.KEY_DATA, data);
					in.putExtra(Constants.KEY_CATEGORIA, categoria);
					in.putExtra(Constants.KEY_MODALITA, modalita);
					in.putExtra(Constants.KEY_SETTORE, settore);
					startActivity(in);

				}
			});
		} else {

		}
	}

	private void showNoConnetionAlert() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.alert_title)
				.setMessage(R.string.alert_message)
				.setCancelable(true)
				.setNegativeButton(R.string.alert_button,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

		AlertDialog alert = builder.create();
		alert.show();
	}

	private void showNoConnetionToast() {

		Context context = getApplicationContext();
		CharSequence text = "Hello toast!";
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(context, text, duration);
		toast.show();

	}

	public void contactMe() {

		Intent i = new Intent(Intent.ACTION_SEND);
		i.setType("message/rfc822");
		i.putExtra(Intent.EXTRA_EMAIL,
				new String[] { "davidev.valentini@gmail.com" });
		i.putExtra(Intent.EXTRA_SUBJECT, R.string.contact_subject);
		i.putExtra(Intent.EXTRA_TEXT, R.string.contact_object);
		try {
			startActivity(Intent.createChooser(i, "Send mail..."));
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(this, R.string.contact_err, Toast.LENGTH_SHORT)
					.show();
		}

	}

}
